﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace FitterTest.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            this.logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            // 获取异常对象  
            Exception exception = context.Exception;

            // 获取异常类型 
            Type exceptionType = exception.GetType();
            context.Result = new JsonResult("出现了异常!")
            {
                StatusCode = 502
            };
            logger.LogError($"全局异常捕获:类型{exceptionType},异常消息{exception.Message}:");
        }
    }
}
